package com.banyuan.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/last")
public class LastTimeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie lastCookie = getCookie(req, "last");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;utf-8");
        Date date = new Date();
        long nowTime = date.getTime();
        if (lastCookie == null) {
            Cookie cookie = new Cookie("last", String.valueOf(nowTime));
            resp.addCookie(cookie);
            resp.getWriter().write("这是你首次访问");
        } else {
            String lastTimeStr = lastCookie.getValue();
            Long lastTime = Long.valueOf(lastTimeStr);
            Date date1 = new Date(lastTime);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String lastTimeString = sdf.format(date1);
            resp.getWriter().write("欢迎回来，你上次访问时间是:" + lastTimeString);
            lastCookie.setValue(String.valueOf(nowTime));
            resp.addCookie(lastCookie);

        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }


    public Cookie getCookie(HttpServletRequest req, String name) {
        Cookie[] cookies = req.getCookies();
        if (cookies == null || cookies.length < 1) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                return cookie;
            }
        }
        return null;
    }
}
